package com.wooming.studentinfosystem.service.impl;

import com.wooming.studentinfosystem.dto.StudentSearchDTO;
import com.wooming.studentinfosystem.mapper.StudentSearchMapper;
import com.wooming.studentinfosystem.service.interf.StudentSearch;
import com.wooming.studentinfosystem.util.PageResult;
import com.wooming.studentinfosystem.util.SearchBaseUtil;
import com.wooming.studentinfosystem.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 学生搜索服务实现
 *
 * @author Wooming
 */
@Service
public class StudentSearchService implements StudentSearch {

    @Autowired
    private StudentSearchMapper studentSearchMapper;

    public PageResult<StudentVO> searchStudents(StudentSearchDTO params) {
        // 构建分页参数
        int offset = (params.getPageNum() - 1) * params.getPageSize();

        // 构建动态SQL参数
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("sortField", validateSortField(params.getSort()));
        searchParams.put("sortOrder", validateOrder(params.getOrder()));
        searchParams.put("offset", offset);
        searchParams.put("pageSize", params.getPageSize());
        searchParams.put("searchBase", SearchBaseUtil.fillSearchBase(params.getSearchBase()));

        // 查询数据
        List<StudentVO> data = studentSearchMapper.selectWithCondition(searchParams);
        Integer total = studentSearchMapper.countWithCondition(searchParams);

        // 构建VO对象
        List<StudentVO> voList = data.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return new PageResult<>(voList, total, params.getPageNum(), params.getPageSize());
    }

    private StudentVO convertToVO(StudentVO student) {
        return student;
    }

    private String validateType(String type) {
        // 验证类型是否合法
        Set<String> validTypes = Set.of("GRADUATE", "UNDERGRAD");
        return validTypes.contains(type) ? type : "GRADUATE";
    }

    private String validateSortField(String sortField) {
        // 验证排序字段是否合法
        Set<String> validSortFields = Set.of("student_id", "name", "age", "class_num");
        return validSortFields.contains(sortField) ? sortField : "student_id";
    }

    private String validateOrder(String order) {
        // 验证排序方式是否合法
        Set<String> validOrders = Set.of("asc", "desc");
        return validOrders.contains(order) ? order : "asc";
    }
}
